<?php
declare(strict_types=1);
namespace app\common\model;
use aphp\core\Model;
class Book extends Model
{
	protected string $table = 'book';
	protected string $pk = 'id';
	// 自动验证
	protected array $validate = [
        ['title', 'required|unique', '标题必须|标题已存在', IF_MUST, AC_BOTH],
        ['sign', 'string|unique', '标识名称必须英文|标识已存在', IF_MUST, AC_BOTH],
        ['summary', 'required', '简介必须', IF_MUST, AC_BOTH],
        ['sort', 'number', '排序值必须是数字', IF_MUST, AC_BOTH],
    ];
	// 自动处理
    protected array $auto = [
        ['status', '1', 'string', IF_MUST, AC_INSERT],
    ];

    protected function _before_insert(array &$data): void
    {
        $data['user_id'] = session('user.id');
    }

    protected function _after_insert(array $data): void
    {
        // 新增时加入成员：创建人
        $member = [
            'book_id' => $data['id'],
            'user_id' => $data['user_id'],
            'role_level' => 3, // 创建者
            'create_time' => time(),
            'status' => 1,
        ];
        db('book_member')->insert($member);
        // 新增时加入默认文档
        $origin = [];
        $origin['book_id'] = $data['id'];
        $origin['sign'] = 'about';
        $origin['title'] = '关于';
        $origin['markdown'] = "## 关于 \n\n欢迎使用".$data['title'];
        $origin['html'] = '<h2>关于</h2><p>欢迎使用'.$data['title'].'</p>';
        $origin['sort'] = 1;
        $origin['user_id'] = $data['user_id'];
        $origin['update_time'] = time();
        $origin['status'] = 1;
        db('doc')->insert($origin);
    }

    protected function _after_delete(array $data): void
    {
        // 删除相关成贡
        db('book_member')->where('book_id', $data['id'])->delete();
        // 删除相关文档
        db('doc')->where('book_id', $data['id'])->delete();
    }
}